package org.lex.utils;

import java.util.ArrayList;

public class MethodNameFormatter {
	private static final String[] PREFIX = { "get", "is", "set" };

	public static String format(String methodName) {
		for (String prefix : PREFIX) {
			if (methodName.startsWith(prefix)) {
				methodName = methodName.substring(prefix.length());
				break;
			}
		}
		return handle(methodName);
	}

	// like "ReadOnly" -> "Read Only"
	private static String handle(String name) {
		if (name.isEmpty())
			return "";
		int len = name.length();
		ArrayList<String> list = new ArrayList<String>();
		StringBuilder buf = new StringBuilder(len + 3);
		buf.append(Character.toUpperCase(name.charAt(0)));
		for (int i = 1, n = len; i < n; i++) {
			char ch = name.charAt(i);
			if (Character.isUpperCase(ch)) {
				list.add(buf.toString());
				buf.setLength(0);
			}
			buf.append(ch);
		}
		if (0 != buf.length())
			list.add(buf.toString());
		buf.setLength(0);
		for (int i = 0, n = list.size(); i < n; i++) {
			String s = list.get(i);
			if (s.length() > 1)
				buf.append(s).append(' ');
			else {
				inner: for (; i < n; i++) {
					String t = list.get(i);
					if (t.length() == 1)
						buf.append(t);
					else {
						buf.append(' ');
						i--;
						break inner;
					}
				}
			}
		}
		return buf.toString();
	}
}
